package com.blb.suanfa;

/**
 * 自定义单向链表
 */
public class MyLinkList {

    /**
     * 链表节点
     */
    public static class MyNode{
        //数据
        Object data;
        //向后指针
        MyNode next;

        public MyNode(Object data, MyNode next) {
            this.data = data;
            this.next = next;
        }
    }

    //头部
    private MyNode head;
    //元素个数
    private int size = 0;

    /**
     * 链表中插入元素
     * @param index
     * @param data
     */
    public void insert(int index,Object data){
        if(index < 0 || index > size){
            throw new RuntimeException("下标越界");
        }
        if(head == null){
            head = new MyNode(data,null);
        }else{
            //从第一个开始找
            MyNode current = head;
            //如果下标不是第一个，向后移动
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }
            //创建新节点，向后指向前面节点的下个节点的下个节点
            MyNode node = new MyNode(data,current.next);
            //前面的节点指向当前节点
            current.next = node;
        }
        size++;
    }

    /**
     * 删除中间的节点
     * @param index
     */
    public void remove(int index){
        if(index < 0 || index > size){
            throw new RuntimeException("下标越界");
        }
        if(index == 0){
            head = head.next;
        }else{
            //定位到要删除节点的前一个节点
            MyNode current = head;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }
            //把前个节点的next指向后一个节点的后一个
            if(current.next != null) {
                current.next = current.next.next;
            }
        }
        size--;
    }

    /**
     * 遍历所有元素
     */
    public void display(){
        MyNode current = head;
        while(current != null){
            System.out.println(current.data);
            current = current.next;
        }
    }

    public static void main(String[] args) {
        MyLinkList myLinkList = new MyLinkList();
        myLinkList.insert(0,99);
        myLinkList.insert(1,66);
        myLinkList.insert(2,77);
        myLinkList.insert(3,88);
        myLinkList.insert(4,44);
        myLinkList.insert(2,89);
        myLinkList.remove(2);
        myLinkList.display();
    }
}
